#pragma once

 #include <stdarg.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
#include <cstdlib>
#include<string>
using namespace std;


#define SIZE 1024

#define Info    0
#define Debug   1
#define Warning 2
#define Error   3
#define Fatal   4

#define Screen    1//向屏幕打印
#define Onefile   2//向单个文件打印
#define Classfile 3//向多个文件打印

#define LogFile "log.txt"

class Log//日志操作
{
public:
    Log()
    {
        printMethod=Screen;
        path="./log/" ;//
    }
    void Enable(int method)//确定打印方式/
    {
        printMethod=method;
    }
    string LevelToString(int level)
    {
        switch(level)
        {
            case Info:
                return "Info";
                break;
            case Debug:
                return "Debug";
                break;
            case Error:
                return "Error";
                break;
            case Fatal:
                return "Fatal";
                break;
            default:
               
                return "NONE";
        }
    }
    void logmessage(int level,const char*format ,...){//发送信息
        time_t t=time(nullptr);
        struct tm *ctime=localtime(&t);//得到时间
        char leftbuffer[SIZE];//左边的时间缓冲区
        snprintf(leftbuffer,sizeof(leftbuffer),"[%s][%d-%d-%d %d:%d:%d]",
                            LevelToString(level).c_str(),
                            ctime->tm_year+1900,ctime->tm_mon+1,ctime->tm_mday,
                            ctime->tm_hour,ctime->tm_min,ctime->tm_sec);
        va_list s;
        va_start(s,format);
        char rightbuffer[SIZE];
        vsnprintf(rightbuffer,sizeof(rightbuffer),format,s);//右边的缓冲区记录具体的内容
        va_end(s);
        
        char logtxt[SIZE*2];
        snprintf(logtxt,sizeof(logtxt),"%s %s\n",leftbuffer,rightbuffer);
        Printlog(level,logtxt);
    }
    void Printlog(int level,const string&logtxt){
       switch(printMethod){
        case Screen:
            cout<<logtxt<<endl;
            break;        
        case Onefile:
            Printone(LogFile,logtxt);
            break;
        case Classfile:
            PrintClass(level,logtxt);        
            break;
       }
    }

    void Printone(const string& file,const string&logtxt)//单文件写入
    {
        string _logname=path+file;
        int fd=open(_logname.c_str(),O_CREAT|O_WRONLY|O_APPEND,0666);
        if(fd<0)
        {
            perror("open");
            return;
        }
        write(fd,logtxt.c_str(),logtxt.size());
        close(fd); 
    }
    void PrintClass(int level,const string&logtxt)//多文件写入
    {
        string filename=LogFile;
        filename+='.';
        filename+=LevelToString(level);
        Printone(filename,logtxt);

    }
    ~Log(){}

private:
    int printMethod;//朝着那个屏幕打印
    string path;//路径
};